package org.ciallo.simplemusicplayer.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.ViewModelProvider;
import com.bumptech.glide.Glide;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.progressindicator.LinearProgressIndicator;
import org.ciallo.simplemusicplayer.R;
import org.ciallo.simplemusicplayer.data.model.Song;
import org.ciallo.simplemusicplayer.dialog.PlayQueueDialogFragment;
import org.ciallo.simplemusicplayer.fragment.HomeFragment;
import org.ciallo.simplemusicplayer.fragment.LocalMusicContainerFragment;
import org.ciallo.simplemusicplayer.fragment.ProfileFragment;
import org.ciallo.simplemusicplayer.viewmodel.SharedViewModel;
import timber.log.Timber;

/**
 * @author Jukomu
 * @Description: 主界面
 * @Package: org.ciallo.simplemusicplayer.activity
 * @Project: SimpleMusicPlayer
 * @name: MainActivity
 * @Date: 2025/5/28-02:04
 * @Filename: MainActivity
 */
public class MainActivity extends AppCompatActivity {

    private BottomNavigationView bottomNavigationView;
    private Toolbar toolbarMain; // 顶部的 Toolbar
    private SharedViewModel sharedViewModel;

    // MiniPlayer 的视图引用
    private View bottomPlayerBarView;
    private ImageView ivBottomCover;
    private TextView tvBottomTitle;
    private TextView tvBottomArtist;
    private ImageButton btnBottomPlayPause;
    private ImageButton btnBottomNext;
    private LinearProgressIndicator progressBottomBar;
    private ImageButton btnBottomPrevious;
    private ImageButton btnBottomPlaylist;
    private SearchView mainSearchView; // 用于持有 SearchView 的引用
    private MenuItem searchMenuItem; // 持有搜索菜单项的引用


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sharedViewModel = new ViewModelProvider(this).get(SharedViewModel.class); // 初始化 SharedViewModel


        toolbarMain = findViewById(R.id.toolbar_main_search); // 这是你 XML 中定义的 Toolbar
        setSupportActionBar(toolbarMain); // 将此 Toolbar 设置为 ActionBar

        bottomNavigationView = findViewById(R.id.bottom_navigation_view_main);
        // sharedViewModel = new ViewModelProvider(this).get(SharedViewModel.class); // 功能开启前先注释

        // 初始化 MiniPlayer 视图
        bottomPlayerBarView = findViewById(R.id.include_main_bottom_player_bar);
        ivBottomCover = bottomPlayerBarView.findViewById(R.id.imageView_bottom_bar_cover);
        tvBottomTitle = bottomPlayerBarView.findViewById(R.id.textView_bottom_bar_title);
        tvBottomArtist = bottomPlayerBarView.findViewById(R.id.textView_bottom_bar_artist);
        btnBottomPlayPause = bottomPlayerBarView.findViewById(R.id.imageButton_bottom_bar_play_pause);
        btnBottomNext = bottomPlayerBarView.findViewById(R.id.imageButton_bottom_bar_next);
        progressBottomBar = bottomPlayerBarView.findViewById(R.id.linearProgressIndicator_bottom_bar);
        btnBottomPrevious = bottomPlayerBarView.findViewById(R.id.imageButton_bottom_bar_previous);
        btnBottomPlaylist = bottomPlayerBarView.findViewById(R.id.imageButton_bottom_bar_playlist);

        bottomNavigationView.setOnItemSelectedListener(item -> {
            Fragment selectedFragment = null;
            int itemId = item.getItemId();
            String title = "";

            if (itemId == R.id.nav_home_main) {
                selectedFragment = new HomeFragment();
                title = "首页";
            } else if (itemId == R.id.nav_local_music_main) {
                selectedFragment = new LocalMusicContainerFragment();
                title = "本地音乐";
            } else if (itemId == R.id.nav_profile_main) {
                selectedFragment = new ProfileFragment();
                title = "我的";
            }

            if (getSupportActionBar() != null) {
                getSupportActionBar().setTitle(title); // 设置Toolbar标题
            }

            // 切换Fragment时，通知系统重新准备选项菜单，这将触发 onPrepareOptionsMenu
            invalidateOptionsMenu();

            if (selectedFragment != null) {
                loadFragment(selectedFragment);
            }
            return true;
        });


        if (savedInstanceState == null) {
            bottomNavigationView.setSelectedItemId(R.id.nav_home_main); // 默认加载首页
        }

        observePlaybackStateForMiniPlayer(); // 观察播放状态以更新 MiniPlayer
        setupMiniPlayerActions();
    }

    /**
     * 加载指定的Fragment到容器中。
     *
     * @param fragment 要加载的Fragment。
     */
    private void loadFragment(Fragment fragment) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.frameLayout_main_fragment_container, fragment);
        transaction.commit();
    }

    /**
     * 观察 MediaPlayerService 的播放状态 LiveData 来更新 MiniPlayer。
     * 现在通过 SharedViewModel 暴露的 LiveData (它直接引用 Service 的静态 LiveData)。
     */
    private void observePlaybackStateForMiniPlayer() {
        sharedViewModel.playbackInfo.observe(this, playbackInfo -> { // 或者 MediaPlayerService.playbackInfo.observe(this, ...
            if (playbackInfo == null || playbackInfo.song == null) {
                bottomPlayerBarView.setVisibility(View.GONE);
                return;
            }
            bottomPlayerBarView.setVisibility(View.VISIBLE);
            updateMiniPlayerUI(
                    playbackInfo.song,
                    playbackInfo.isPlaying,
                    playbackInfo.currentPositionMs,
                    playbackInfo.durationMs
            );
        });
    }

    /**
     * 更新 MiniPlayer 的UI。
     *
     * @param song              当前歌曲。
     * @param isPlaying         是否正在播放。
     * @param currentPositionMs 当前播放进度。
     * @param durationMs        歌曲总时长。
     */
    private void updateMiniPlayerUI(@Nullable Song song, boolean isPlaying, long currentPositionMs, long durationMs) {
        if (song == null) {
            bottomPlayerBarView.setVisibility(View.GONE); // 确保无歌时隐藏
            return;
        }
        bottomPlayerBarView.setVisibility(View.VISIBLE);

        tvBottomTitle.setText(song.getTitle());
        tvBottomArtist.setText(String.format("%s - %s", song.getArtistName(), song.getAlbumName()));

        Uri coverUri = null;
        if (song.getAlbumArtUri() != null && !song.getAlbumArtUri().isEmpty()) {
            coverUri = Uri.parse(song.getAlbumArtUri());
        }
        Glide.with(this)
                .load(coverUri)
                .placeholder(R.drawable.default_album_art)
                .error(R.drawable.default_album_art)
                .into(ivBottomCover);

        btnBottomPlayPause.setImageResource(isPlaying ? R.drawable.ic_notification_pause : R.drawable.ic_notification_play);

        if (durationMs > 0) {
            progressBottomBar.setMax((int) durationMs);
            progressBottomBar.setProgress((int) currentPositionMs);
        } else {
            progressBottomBar.setMax(100);
            progressBottomBar.setProgress(0);
        }
    }


    /**
     * 为 MiniPlayer 上的控件设置点击事件。
     */
    private void setupMiniPlayerActions() {
        bottomPlayerBarView.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, PlayerActivity.class);
            startActivity(intent);
        });

        btnBottomPlayPause.setOnClickListener(v -> sharedViewModel.togglePlayPause()); // 通过 SharedViewModel
        btnBottomNext.setOnClickListener(v -> sharedViewModel.playNext());            // 通过 SharedViewModel
        btnBottomPrevious.setOnClickListener(v -> sharedViewModel.playPrevious());  // 通过 SharedViewModel

        btnBottomPlaylist.setOnClickListener(v -> {
            PlayQueueDialogFragment.newInstance().show(getSupportFragmentManager(), PlayQueueDialogFragment.TAG);
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        Timber.d("MainActivity onCreateOptionsMenu");
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_activity_menu, menu);

        searchMenuItem = menu.findItem(R.id.action_search_main);
        mainSearchView = (SearchView) searchMenuItem.getActionView();

        if (mainSearchView != null) {
            mainSearchView.setQueryHint("搜索..."); // 可以根据当前Fragment动态改变
            mainSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String query) {
                    Timber.d("SearchView: onQueryTextSubmit: %s", query);
                    // 不论哪个页面提交，都更新 SharedViewModel，由各Fragment决定如何响应
                    sharedViewModel.setSearchQuery(query);
                    mainSearchView.clearFocus(); // 提交后清除焦点，收起软键盘
                    // searchMenuItem.collapseActionView(); // 提交后可以折叠，也可以不折叠让用户继续搜索
                    return true;
                }

                @Override
                public boolean onQueryTextChange(String newText) {
                    Timber.d("SearchView: onQueryTextChange: %s", newText);
                    // 实时更新 SharedViewModel 中的查询词
                    sharedViewModel.setSearchQuery(newText);
                    return true;
                }
            });

            searchMenuItem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
                @Override
                public boolean onMenuItemActionExpand(MenuItem item) {
                    Timber.d("SearchView: Expanded");
                    // SearchView 展开时的逻辑
                    // 如果有之前保存的查询词，可以在这里填充
                    String currentQuery = sharedViewModel.currentSearchQuery.getValue();
                    if (currentQuery != null && !currentQuery.isEmpty()) {
                        mainSearchView.setQuery(currentQuery, false); // false表示不提交查询
                    }
                    return true;
                }

                @Override
                public boolean onMenuItemActionCollapse(MenuItem item) {
                    Timber.d("SearchView: Collapsed");
                    // SearchView 折叠/关闭时的逻辑
                    sharedViewModel.setSearchQuery(""); // 清空搜索查询
                    return true;
                }
            });
        } else {
            Timber.e("MainActivity: mainSearchView is null in onCreateOptionsMenu!");
        }
        return true;
    }

    /**
     * 检查当前显示的Fragment是否是支持搜索的页面（首页或本地音乐页）。
     */
    private boolean isCurrentFragmentSearchable() {
        int selectedItemId = bottomNavigationView.getSelectedItemId();
        return selectedItemId == R.id.nav_local_music_main || selectedItemId == R.id.nav_home_main;
    }


    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        Timber.d("MainActivity onPrepareOptionsMenu");
        if (searchMenuItem != null) {
            boolean isSearchable = isCurrentFragmentSearchable();
            Timber.d("Is current fragment searchable? %b", isSearchable);
            searchMenuItem.setVisible(isSearchable);

            if (isSearchable) {
                // 如果页面可搜索，确保SearchView的状态正确
                // （例如，如果之前是展开的，并且现在应该展开，则展开它）
                String currentQuery = sharedViewModel.currentSearchQuery.getValue();
                if (mainSearchView != null && currentQuery != null && !currentQuery.isEmpty() && !mainSearchView.isIconified()) {
                    // 如果希望在切换回可搜索页面时自动展开并填充上次的查询：
                    searchMenuItem.expandActionView();
                    mainSearchView.setQuery(currentQuery, false);
                }
            } else {
                // 如果页面不可搜索，并且SearchView当前是展开的，则折叠它
                if (mainSearchView != null && !mainSearchView.isIconified()) {
                    Timber.d("Collapsing SearchView because fragment is not searchable.");
                    searchMenuItem.collapseActionView(); // 折叠
                    sharedViewModel.setSearchQuery(""); // 确保查询也被清空
                }
            }
        }
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
